package com.webserver.servlet;
import com.webserver.http.*;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

public class register {
    public void server(HttpRequest httpRequest,HttpResponse httpResponse){
        System.out.println("噗噜噜");
        //1.获取数据
        String username = httpRequest.getQueryMap("username");
        String password = httpRequest.getQueryMap("password");
        String date = httpRequest.getQueryMap("date");
        String age = httpRequest.getQueryMap("age");
        if(username==null||password==null||age==null||!age.matches("\\d+")) {
            httpResponse.setFile(new File("./Webapps/myweb/error.html"));
            System.out.println("喵喵喵+");
            return;
        }
        //2.写入数据
        try(RandomAccessFile raf = new RandomAccessFile("user.dat","rw")){
            //先将指针移动到文件末尾以便追加记录
            raf.seek(raf.length());
            //写入用户名
            byte[] data = username.getBytes("UTF-8");
            //将数组扩容到32字节
            data = Arrays.copyOf(data, 32);
            raf.write(data);
            data = password.getBytes("UTF-8");
            data = Arrays.copyOf(data, 32);
            raf.write(data);
            data = date.getBytes("UTF-8");
            data = Arrays.copyOf(data, 32);
            raf.write(data);
            data = age.getBytes("UTF-8");
            data = Arrays.copyOf(data, 32);
            raf.write(data);
            //3.反馈页面
            httpResponse.setFile(new File("./Webapps/myweb/register_success.html"));
            System.out.println("注册完毕!");
        }catch(IOException e){
            e.printStackTrace();
        }

    }
}
